package cn.edu.scnu.semart.goods.controller;


import cn.edu.scnu.semart.goods.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/images")
//@CrossOrigin
public class ImageController {

    @Autowired
    private ImageService imageService;

    // 图片上传并压缩
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("image") MultipartFile image) {
        try {
            return imageService.uploadAndCompressImage(image);
        } catch (IOException e) {
            e.printStackTrace();
            return "图片上传或压缩失败";
        }
    }

    // 图片下载接口（下载压缩后的图片）
    @GetMapping("/download/{imageName}")
    public ResponseEntity<FileSystemResource> downloadImage(@PathVariable String imageName) throws IOException {
        File compressedImage = imageService.downloadCompressedImage(imageName);

        FileSystemResource resource = new FileSystemResource(compressedImage);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + compressedImage.getName())
                .contentType(MediaType.IMAGE_JPEG) // 根据实际情况选择正确的类型
                .body(resource);
    }
}